import { Button, message } from 'antd';
import { downloadTemplateFile } from '../service';

const DownloadTemplate = () => (
  <Button
    onClick={async () => {
      const res = await downloadTemplateFile();
      try {
        if (res) {
          const filename = 'multi_create_iotSim.xlsx';
          const downloadElement = document.createElement('a');
          const herf = window.URL.createObjectURL(
            new Blob([res], {
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            }),
          );
          downloadElement.href = herf;
          downloadElement.download = filename;
          document.body.appendChild(downloadElement);
          downloadElement.click();
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(herf); // 释放blob对象
          return true;
        }
        message.error({ content: res?.message || '下载失败', key: 'd_template' });
        return false;
      } catch (err) {
        message.error({ content: String(err), key: 'd_template' });
        return false;
      }
    }}
  >
    下载批量创建模板
  </Button>
);

export default DownloadTemplate;
